package com.zhouyu;

import com.zhouyu.service.UserService;
import org.springframework.cglib.proxy.*;

import java.lang.reflect.Method;

public class CglibTest {
	public static void main(String[] args) {
		UserService target = new UserService();
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(UserService.class);
		enhancer.setCallbacks(new Callback[] { new MethodInterceptor() {
			/**
			 *
			 * @param o 代理对象
			 * @param method target方法
			 * @param objects 参数
			 * @param methodProxy  代理方法
			 * target 被代理对象
			 * @return
			 * @throws Throwable
			 */
			@Override
			public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
				System.out.println("--before-- test");
				Object result = methodProxy.invoke(target, objects);
				result = methodProxy.invokeSuper(o, objects);  //cglib 执行代理类父类的方法
				System.out.println("--after-- test");
				return result;
			}
		}, (MethodInterceptor) (o, method, objects, methodProxy) -> {
            System.out.println("--before-- a");
            Object result = methodProxy.invoke(target, objects);
            result = methodProxy.invokeSuper(o, objects);  //cglib 执行代理类父类的方法
            System.out.println("--after-- a");
            return result;
        }
        });
		enhancer.setCallbackFilter(new CallbackFilter() {
			@Override
			public int accept(Method method) {
				if (method.getName().equals("test")) {
					return 0;
				}else {
					return 1;
				}
			}
		});
		UserService userService = (UserService) enhancer.create();
		userService.test();
		userService.a();

	}
}
